package cn.com.chengmandian.bike.service.impl;

import cn.com.chengmandian.bike.mapper.EbMemberDepositMapper;
import cn.com.chengmandian.bike.model.EbDepositCard;
import cn.com.chengmandian.bike.model.EbMemberDeposit;
import cn.com.chengmandian.bike.model.vo.MemberDepositVo;
import cn.com.chengmandian.bike.service.IEbDepositCardService;
import cn.com.chengmandian.bike.service.IEbMemberDepositService;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;

/**
 * <p>
 * 电单车运营-用户免押卡购买记录 服务实现类
 * </p>
 *
 * @author AutoGenerator
 * @since 2022-01-19
 */
@Service
public class EbMemberDepositServiceImpl extends ServiceImpl<EbMemberDepositMapper, EbMemberDeposit> implements IEbMemberDepositService {
    @Autowired
    private EbMemberDepositMapper memberDepositMapper;

    @Autowired
    private IEbDepositCardService depositCardService;

    /**
     * 获取最后一个到期的骑行卡
     */
    @Override
    public MemberDepositVo getLastDeposit(Integer areaId, Integer memberId) {
        return memberDepositMapper.getLastDeposit(areaId, memberId);
    }

    /**
     * 获取生效中的骑行卡
     */
    @Override
    public EbMemberDeposit getMemberAvailableRecord(Integer areaId, Integer memberId) {
        String now = DateUtil.now();
        return this.getOne(new LambdaQueryWrapper<EbMemberDeposit>()
                .eq(EbMemberDeposit::getAreaId, areaId)
                .eq(EbMemberDeposit::getMemberId, memberId)
                .le(EbMemberDeposit::getStartTime, now)
                .ge(EbMemberDeposit::getExpireTime, now)
                .last("limit 1"));
    }

    @Override
    public EbMemberDeposit payCard(Integer memberId, Integer cardId, BigDecimal money) {
        Date now = new Date();
        Date startTime = now;
        EbDepositCard depositCard = depositCardService.getById(cardId);
        Date expireTime = DateUtil.offsetDay(now, depositCard.getDays());
        EbMemberDeposit memberDeposit = new EbMemberDeposit();
        memberDeposit.setAreaId(depositCard.getAreaId());
        memberDeposit.setMemberId(memberId);
        memberDeposit.setCardId(cardId);
        memberDeposit.setMoney(money);
        memberDeposit.setStartTime(startTime);
        memberDeposit.setExpireTime(expireTime);
        this.save(memberDeposit);
        return memberDeposit;
    }

    @Override
    public long getCount(Integer areaId, Integer memberId) {
        return this.count(new LambdaQueryWrapper<EbMemberDeposit>()
                .eq(EbMemberDeposit::getAreaId, areaId)
                .eq(EbMemberDeposit::getMemberId, memberId));
    }
}
